package com.jms.tomcat.http;

import com.jms.tomcat.core.JmsServletContext;
import com.jms.tomcat.stream.RequestServletInputStream;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.Principal;
import java.util.*;

public class JmsRequest implements HttpServletRequest {

    private String method; //请求方法
    private String uri; //请求uri
    private final Map<String, String> parameterMap = new HashMap<>(); //请求参数
    private final Map<String, String> requestHead = new HashMap<>(); //请求头

    private final Map<String, Cookie> cookies = new HashMap<>(); //请求cookie
    private int contentLength; //请求体长度
    private String queryString; //请求中?后面的部分
    private final JmsRequestDispatcher requestDispatcher;
    private final ServletInputStream servletInputStream;
    /**
     * servlet上下问
     */
    private final JmsServletContext servletContext;

    public JmsRequest(InputStream inputStream, JmsServletContext servletContext) throws IOException, ServletException {
        this.servletContext = servletContext;
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
        String requestLine = reader.readLine();
        if (requestLine != null && requestLine.contains("HTTP")) {
            String[] requestLineArr = requestLine.split(" ");
            if (requestLineArr.length > 2) {
                this.method = isNotNull(requestLineArr[0].toUpperCase());
                //解析uri和参数
                int index = requestLineArr[1].indexOf("?");
                if (index == -1) {
                    this.uri = isNotNull(requestLineArr[1]);
                } else {
                    this.uri =  isNotNull(requestLineArr[1].substring(0, index));
                    this.queryString = isNotNull(requestLineArr[1].substring(index + 1));
                    if (index != requestLineArr.length - 1) {
                        String[] parameterArr = requestLineArr[1].substring(index + 1).split("&");
                        for (String parameterItem: parameterArr) {
                            String[] paramKeyValue = parameterItem.split("=");
                            if (paramKeyValue.length >= 2) {
                                String key = paramKeyValue[0];
                                StringBuilder value = new StringBuilder(paramKeyValue[1]);
                                for (int i = 2; i < paramKeyValue.length; i++) {
                                    value.append("=").append(paramKeyValue[i]);
                                }
                                parameterMap.put(key, value.toString());
                            }
                        }
                    }
                }
            }

            //解析请求头
            String head;
            while ((head = reader.readLine()) != null && !head.trim().isEmpty()) {
                String[] headKeyValue = head.split(":");
                if (headKeyValue.length >= 2) {
                    String key = headKeyValue[0];
                    StringBuilder value = new StringBuilder(headKeyValue[1]);
                    for (int i = 2; i < headKeyValue.length; i++) {
                        value.append(":").append(headKeyValue[i]);
                    }
                    requestHead.put(key.trim(), value.toString().trim());
                }
            }

            //解析cookie
            if (requestHead.containsKey("Cookie")) {
                String[] cookieArr = requestHead.get("Cookie").split(";");
                for (String cookieItem: cookieArr) {
                    String[] cookieKeyValue = cookieItem.split("=");
                    if (cookieKeyValue.length >= 2) {
                        String key = cookieKeyValue[0];
                        StringBuilder value = new StringBuilder(cookieKeyValue[1].trim());
                        for (int i = 2; i < cookieKeyValue.length; i++) {
                            value.append("=").append(cookieKeyValue[i].trim());
                        }
                        cookies.put(key, new Cookie(key.trim(), value.toString()));
                    }
                }
            }

            if (requestHead.containsKey("Content-Length")) {
                contentLength = Integer.parseInt(requestHead.get("Content-Length"));
            }

            //解析请求体
            StringBuilder body = new StringBuilder();
            char[] bt = new char[1024];
            //从请求头中获取请求体长度
            if (requestHead.containsKey("Content-Length")) {
                contentLength = Integer.parseInt(requestHead.get("Content-Length"));
                int readLength = 0;
                while (readLength < contentLength && reader.ready()) {
                    int index = reader.read(bt);
                    body.append(bt, 0, index);
                    readLength += index;
                }
            } else {
                while (reader.ready()) {
                    int index = reader.read(bt);
                    body.append(bt, 0, index);
                }
            }
            servletInputStream = new RequestServletInputStream(body.toString().getBytes(StandardCharsets.UTF_8));
//            requestBody = body.toString();
        } else {
            throw new ServletException(JmsServletError.BAD_REQUEST);
        }
        requestDispatcher = new JmsRequestDispatcher();
    }

    public <T> T isNotNull(T o) throws ServletException {
        if (o == null) {
            throw new ServletException(JmsServletError.BAD_REQUEST);
        }
        return o;
    }

    @Override
    public String getAuthType() {
        return null;
    }

    @Override
    public Cookie[] getCookies() {
        return cookies.values().toArray(new Cookie[0]);
    }

    @Override
    public long getDateHeader(String name) {
        return 0;
    }

    @Override
    public String getHeader(String name) {
        return requestHead.get(name);
    }

    @Override
    public Enumeration<String> getHeaders(String name) {
        return null;
    }

    @Override
    public Enumeration<String> getHeaderNames() {
        return new Vector<>(requestHead.keySet()).elements();
    }

    @Override
    public int getIntHeader(String name) {
        if (requestHead.containsKey(name)) {
            return Integer.parseInt(requestHead.get(name));
        }
        return 0;
    }

    @Override
    public String getMethod() {
        return method;
    }

    @Override
    public String getPathInfo() {
        return null;
    }

    @Override
    public String getPathTranslated() {
        return null;
    }

    @Override
    public String getContextPath() {
        int index = uri.indexOf("/", 1);
        return uri.substring(0, index);
    }

    @Override
    public String getQueryString() {
        return queryString;
    }

    @Override
    public String getRemoteUser() {
        return null;
    }

    @Override
    public boolean isUserInRole(String role) {
        return false;
    }

    @Override
    public Principal getUserPrincipal() {
        return null;
    }

    @Override
    public String getRequestedSessionId() {
        return null;
    }

    @Override
    public String getRequestURI() {
        return uri;
    }

    @Override
    public StringBuffer getRequestURL() {
        return null;
    }

    @Override
    public String getServletPath() {
        return null;
    }

    @Override
    public HttpSession getSession(boolean create) {
        return null;
    }

    @Override
    public HttpSession getSession() {
        return null;
    }

    @Override
    public String changeSessionId() {
        return null;
    }

    @Override
    public boolean isRequestedSessionIdValid() {
        return false;
    }

    @Override
    public boolean isRequestedSessionIdFromCookie() {
        return false;
    }

    @Override
    public boolean isRequestedSessionIdFromURL() {
        return false;
    }

    @Override
    public boolean isRequestedSessionIdFromUrl() {
        return false;
    }

    @Override
    public boolean authenticate(HttpServletResponse response) {
        return false;
    }

    @Override
    public void login(String username, String password) {

    }

    @Override
    public void logout() {

    }

    @Override
    public Collection<Part> getParts() {
        return null;
    }

    @Override
    public Part getPart(String name) {
        return null;
    }

    @Override
    public <T extends HttpUpgradeHandler> T upgrade(Class<T> handlerClass) {
        return null;
    }

    @Override
    public Object getAttribute(String name) {
        return null;
    }

    @Override
    public Enumeration<String> getAttributeNames() {
        return null;
    }

    @Override
    public String getCharacterEncoding() {
        return null;
    }

    @Override
    public void setCharacterEncoding(String env) {

    }

    @Override
    public int getContentLength() {
        return contentLength;
    }

    @Override
    public long getContentLengthLong() {
        return contentLength;
    }

    @Override
    public String getContentType() {
        return requestHead.get("Content-Type");
    }

    @Override
    public ServletInputStream getInputStream() {
        return servletInputStream;
    }

    @Override
    public String getParameter(String name) {
        return parameterMap.get(name);
    }

    @Override
    public Enumeration<String> getParameterNames() {
        return null;
    }

    @Override
    public String[] getParameterValues(String name) {
        return new String[0];
    }

    @Override
    public Map<String, String[]> getParameterMap() {
        return null;
    }

    @Override
    public String getProtocol() {
        return null;
    }

    @Override
    public String getScheme() {
        return null;
    }

    @Override
    public String getServerName() {
        return null;
    }

    @Override
    public int getServerPort() {
        return 0;
    }

    @Override
    public BufferedReader getReader() {
        return null;
    }

    @Override
    public String getRemoteAddr() {
        return null;
    }

    @Override
    public String getRemoteHost() {
        return null;
    }

    @Override
    public void setAttribute(String name, Object o) {

    }

    @Override
    public void removeAttribute(String name) {

    }

    @Override
    public Locale getLocale() {
        return null;
    }

    @Override
    public Enumeration<Locale> getLocales() {
        return null;
    }

    @Override
    public boolean isSecure() {
        return false;
    }

    @Override
    public RequestDispatcher getRequestDispatcher(String path) {
        requestDispatcher.setPath(path);
        return requestDispatcher;
    }

    @Override
    public String getRealPath(String path) {
        return null;
    }

    @Override
    public int getRemotePort() {
        return 0;
    }

    @Override
    public String getLocalName() {
        return null;
    }

    @Override
    public String getLocalAddr() {
        return null;
    }

    @Override
    public int getLocalPort() {
        return 0;
    }

    @Override
    public ServletContext getServletContext() {
        return servletContext;
    }

    @Override
    public AsyncContext startAsync() throws IllegalStateException {
        return null;
    }

    @Override
    public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse) throws IllegalStateException {
        return null;
    }

    @Override
    public boolean isAsyncStarted() {
        return false;
    }

    @Override
    public boolean isAsyncSupported() {
        return false;
    }

    @Override
    public AsyncContext getAsyncContext() {
        return null;
    }

    @Override
    public DispatcherType getDispatcherType() {
        return null;
    }
}
